package com.ipan.jfinal.render;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import com.ipan.kits.io.FileUtil;
import com.ipan.kits.text.MoreStringUtil;
import com.jfinal.render.Render;

/**
 * 渲染图片
 * 
 * @author iPan
 * @version 2018-05-17
 */
public class ImageRender extends Render {
	
	private File file = null;
	private static Map<String, String> contentTypes = new HashMap<String, String>();
	
	// 常见图片类型
	static {
		contentTypes.put("ico", "image/x-icon");
		contentTypes.put("gif", "image/gif");
		contentTypes.put("jpe", "image/jpeg");
		contentTypes.put("jpeg", "image/jpeg");
		contentTypes.put("jpg", "image/jpeg");
		contentTypes.put("png", "image/png");
	}
	
	public ImageRender(File file) {
		this.file = file;
	}

	@Override
	public void render() {
		String extName = FileUtil.getFileExtension(file.getName()).toLowerCase();
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType(getImageContentType(extName));
		
		ServletOutputStream sos = null;
		FileInputStream fin = null;
		try {
			byte[] buf = new byte[1024];
			fin = new FileInputStream(file);
			sos = response.getOutputStream();
			int len = fin.read(buf);
			while (len > -1) {
				sos.write(buf, 0, len);
				len = fin.read(buf);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("找不到文件", e);
		} catch (IOException e) {
			throw new RuntimeException("读写文件出错", e);
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
				}
			}
			if (sos != null) {
				try {
					sos.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	private String getImageContentType(String extName) {
		String type = contentTypes.get(extName);
		return MoreStringUtil.getStr(type, "image/jpeg"); 
	}

}
